package ttOrder.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import ttOrder.model.Order;
import ttOrder.vo.OrderVO;

@Repository
public class OrderDAOImpl extends BaseHibernateDAO<Order> implements IOrderDAO {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	public OrderDAOImpl() {

	}

	@Autowired
	private SessionFactory sessionFactory;

	public Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public List<Order> findAllOrder(Integer id) {
		Session session = getSession();
		String hql = " from Order WHERE	ORDERID=" + id;
		@SuppressWarnings("unchecked")
		List<Order> order = session.createQuery(hql).list();
		return order;
	}

	@Override
	public Order getOrderById(Integer id) {
		Session session = getSession();
		return (Order) session.get(Order.class, id);
	}

	@Override
	public void createOrder(Order order) throws Exception {
		Session session = getSession();
		session.save(order);
	}

	@Override
	public void editOrder(Integer id) throws Exception {
		Order order = this.get(id);
		if (order != null) {
			this.update(order);
		}
	}

	@Override
	public void deleteOrder(Integer id) throws Exception {
		Order order = this.get(id);
		if (order != null) {
			this.delete(order);
		}
	}

	@Override
	public void createOrderVO(OrderVO order) throws Exception {
		// TODO Auto-generated method stub
		String sql = "INSERT	INTO	orderdetail	VALUES	(?,?,?,?)";
		jdbcTemplate.update(sql,
				new Object[] { order.getId(), order.getOrderId(), order.getFoodId(), order.getFoodcount() });
	}

	public OrderVO getOrder(Integer id) {
		String sql = " SELECT * FROM orderdetail WHERE ID=?";
		return jdbcTemplate.queryForObject(sql, new Object[] { id }, new RowMapper<OrderVO>() {
			public OrderVO mapRow(ResultSet rs, int num) throws SQLException {
				OrderVO ordervo = new OrderVO();
				ordervo.setId(rs.getInt("ID"));
				ordervo.setFoodId(rs.getInt("FOOD_ID"));
				return ordervo;
			}
		});

	}

	public Integer create(OrderVO ordervo) throws Exception {
		String sql = "INSERT	INTO orderdetail	VALUES	(?,?,?,?)";
		return jdbcTemplate.update(sql, new Object[] { ordervo.getId() }, ordervo.getFoodId(), ordervo.getFoodcount(),
				ordervo.getOrderId());
	}



}
